from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings
from django.shortcuts import render, redirect, HttpResponse
import datetime
import re


class RbacMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 1.获取当前请求url
        current_url = request.path_info
        # 2.登录认证 如果是登录的话直接返回，就走不到下面
        for reg in settings.WHITE_LIST:
            if re.match(reg, current_url):
                return
        # 3.获取当前用户的所有权限
        permissions_dict = request.session.get(settings.PERMISSIONS_LIST, '')
        # 默认没有权代表没有登录
        if not permissions_dict:
            return redirect('login')

        # 存session
        request.breadcrumb_list = [
            {'title': '首页', 'url': '/'},
        ]

        flag = False
        # 4.进行比对,通过re.math(数据库权限路由,当前路由)math 前匹配后
        for item in permissions_dict.values():
            id = item['id']
            pid = item['pid']
            pname = item['pname']
            reg = '^%s$' % item.get('url')  # 防止路由没有写但是匹配上了
            # print(reg, current_url)
            if re.match(reg, current_url):
                flag = True
                # 如果有pid 代表其是非菜单权限url 比如客户添加/删除
                if pid:
                    # 把当前非菜单权限的id保存起来
                    # 访问的是客户添加/...
                    request.current_menu_id = pid
                    request.breadcrumb_list.extend([
                        # 其父级目录
                        {'title': permissions_dict[pname]['title'], 'url': permissions_dict[pname]['url']},
                        # 客户添加
                        {'title': item['title'], 'url': item['url']}
                    ])
                else:
                    request.current_menu_id = id
                    # 访问二级菜单
                    request.breadcrumb_list.extend([
                        {'title': item['title'], 'url': item['url']}
                    ])
                break
        if not flag:
            return HttpResponse('没有权限，请联系相关负责人')
